package com.dtguai.admin.web.sys.service.impl;

import com.dtguai.admin.base.service.impl.BaseServiceImpl;
import com.dtguai.admin.page.PageModel;
import com.dtguai.admin.util.redis.RedisUtil;
import com.dtguai.admin.web.sys.dao.SysDefRoleMenuDao;
import com.dtguai.admin.web.sys.model.SysDefRoleMenu;
import com.dtguai.admin.web.sys.service.SysDefRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
   * @author guoLiang
   * @date 2018-12-11 02:43:07
   */
@Service("sysDefRoleMenuService")
public class SysDefRoleMenuServiceImpl extends BaseServiceImpl<SysDefRoleMenu> implements SysDefRoleMenuService {
	
	@Autowired
	RedisUtil redisUtil;
	
	/**
     * 根据条件查询  不分页
     */
    @Override
    public List<SysDefRoleMenu> selectBySysDefRoleMenu(PageModel sysDefRoleMenu) {
		return selectBySysDefRoleMenuPage(sysDefRoleMenu, false, SysDefRoleMenu.class);
    }

	@Override
	public List<SysDefRoleMenu> selectBySysDefRoleMenuPage(PageModel sysDefRoleMenu,boolean page,Class<?> clas) {
		return selectByExample(super.getExample(sysDefRoleMenu,page,clas));
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveOrUpdate(Integer roleId, List<Integer> menuIdList) {
		//先删除角色与菜单关系
		SysDefRoleMenu drm = new SysDefRoleMenu();
		drm.setSysDefRoleId(roleId);
		deleteByWhere(drm);

		if(menuIdList == null || menuIdList.size() == 0){
			return ;
		}

		//保存角色与菜单关系
		List<SysDefRoleMenu> list = new ArrayList<>(menuIdList.size());
		menuIdList.forEach(x ->{
			SysDefRoleMenu rm = new SysDefRoleMenu();
			rm.setSysDefMenuId(x);
			rm.setSysDefRoleId(roleId);
			list.add(rm);
		});
		((SysDefRoleMenuDao) getMapper()).insertList(list);
	}

	/**
	 * 根据角色ID，获取菜单ID列表
	 */
	@Override
	public List<Integer> getMenuIdList(Integer roleId){
		SysDefRoleMenu rm = new SysDefRoleMenu();
		rm.setOrderBy("id asc");
		rm.setSysDefRoleId(roleId);
		List<SysDefRoleMenu> roleMenuList = selectBySysDefRoleMenu(rm);
		if(null!=roleMenuList){
			return roleMenuList.stream().map(x -> x.getSysDefMenuId()).collect(Collectors.toList());
		}
		return null;
	}

	/**
	 * 根据角色ID数组，批量删除
	 */
	@Override
	public Integer deleteBatchById(List<Integer> roleIds) {
		Example example = new Example(SysDefRoleMenu.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andIn("sysDefRoleId",roleIds);
		return ((SysDefRoleMenuDao) getMapper()).deleteByExample(example);
	}

}